<template>
	<view class="home-container">
		<!-- 保持不变的雨量站和今日雨量部分 -->
		<view class="header">
			<view class="station-name">
				<text class="label">雨量站：</text>
				<text class="value">{{arrName}}</text>
			</view>
		</view>
		<view class="card today-rainfall">
			<view class="card-content">
				<text class="card-label">已报雨量：</text>
				<view class="" v-if="typedele == 0">
					{{meaTime}}
				</view>
				<view class="" v-if="typedele == 1">
					{{displayTime}}
				</view>
				<view class="rainfall-value">
					<text class="number">{{todayRainfall}}</text>
					<text class="unit">mm</text>
				</view>
			</view>
			<view class="card-icon">
				<image src="/static/yuliangss.png" mode=""></image>
			</view>
		</view>

		<!-- 修改为横向排列的表单部分 -->
		<view class="form-row">
			<view class="form-item">
				<text class="form-label">降雨日期：</text>
				<view class="" v-if="typedele == 0">
					{{meaTime}}
				</view>
				<view class="form-input" v-if="typedele == 1">
					<view class="time-switcher">
						<view class="arrow-btn" @click="switchTime(-1)" :class="{ disabled: isToday }">
							<u-icon name="arrow-left" size="24" color="#4a90e2"></u-icon>
						</view>
						<view class="current-time">
							{{ displayTime }}
						</view>
						<view class="arrow-btn" @click="switchTime(1)">
							<u-icon name="arrow-right" size="24" :color="isToday ? '#cccccc' : '#4a90e2'"></u-icon>
						</view>
					</view>
				</view>
			</view>
			<!-- 			<view class="form-item">
				<text class="form-label">上传经度：</text>
				<view class="form-input">
					<u--input v-model="mapLon" placeholder="请输入" border="bottom" clearable></u--input>
				</view>
			</view>
			<view class="form-item">
				<text class="form-label">上传纬度：</text>
				<view class="form-input">
					<u--input v-model="mapLat" placeholder="请输入" border="bottom" clearable></u--input>
				</view>
			</view> -->
			<view class="form-item">
				<text class="form-label">降雨量：</text>
				<view class="form-input">
					<u--input type="digit" v-model="rainFall" placeholder="请输入" border="bottom" clearable></u--input>
					<text class="unit">mm</text>
				</view>
			</view>

			<view class="form-item">
				<text class="form-label">更新方式：</text>
				<view class="form-input">
					<uni-data-checkbox mode="tag" v-model="method" :localdata="typelist"
						selectedColor="#4a90e2"></uni-data-checkbox>
				</view>
			</view>
			<view class="form-item">
				<text class="form-label">测报人：</text>
				<view class="form-input">
					<u--input v-model="informant" placeholder="请输入" border="bottom" clearable></u--input>
				</view>
			</view>
		</view>

		<!-- 保持不变的按钮部分 -->
		<view class="action-buttons">
			<u-button shape="circle" type="primary" text="上传数据" @click="successFn" :customStyle="{
          height: '90rpx',
          fontSize: '34rpx',
          marginBottom: '20rpx'
        }"></u-button>
			<u-button shape="circle" text="取消返回" @click="errorFn" :customStyle="{
          height: '90rpx',
          fontSize: '34rpx',
          color: '#666',
          backgroundColor: '#f5f5f5'
        }"></u-button>
		</view>

		<u-modal :show="modalshow" title="确认上传" content="请确认雨量数据无误" showCancelButton @confirm="confirmFn"
			@cancel="cancelFn" :asyncClose="true"></u-modal>
	</view>
</template>

<script>
	import dayjs from '@/common/dayjs.min.js';
	export default {
		data() {
			return {
				currentDate: new Date(), //当前时间
				modalshow: false,
				date: '',
				rsId: 0,
				rainFall: null,
				informant: '',
				arrName: '',
				method: null, //上报类型
				typelist: [{
					text: '追加',
					value: 0
				}, {
					text: '替换',
					value: 1
				}],
				todayRainfall: '', //今日雨量
				mapLon: '', //经度
				mapLat: '', //纬度
				meaTime: '', //修改传值时间
				typedele: '' //是否修改类型
			}
		},
		computed: {
			displayTime() {
				const year = this.currentDate.getFullYear()
				const month = this.currentDate.getMonth() + 1
				const day = this.currentDate.getDate()
				return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
			},
			isToday() {
				const today = new Date()
				return (
					this.currentDate.getFullYear() === today.getFullYear() &&
					this.currentDate.getMonth() === today.getMonth() &&
					this.currentDate.getDate() === today.getDate()
				)
			}
		},
		onLoad(option) {
			this.rsId = option.id
			this.arrName = option.name
			this.todayRainfall = option.todayRainfall //今日雨量
			this.informant = option.informant //leixi 
			this.typedele = option.type //leixi 
			if (this.typedele == 0) {
				this.meaTime = option.meaTime //修改日期
			}
			if (this.typedele == 1) {
				this.meaTime = this.displayTime //修改日期
			}

			this.latlonFn() //经纬度
			console.log('this', option);
		},
		methods: {
			// 经纬度
			latlonFn() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						this.mapLon = res.longitude
						this.mapLat = res.latitude
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
					}
				});
			},
			confirmFn() {
				this.uploadHistoryFn()
				this.modalshow = false
			},
			cancelFn() {
				this.modalshow = false
			},
			successFn() {
				if (this.rsId != 0 && this.rainFall != null && this.informant != '') {
					this.modalshow = true
				} else {
					uni.showToast({
						title: '请填写完整信息',
						icon: 'none',
						duration: 1500
					});
				}
			},
			errorFn() {
				uni.navigateBack({
					delta: 1
				});
			},
			uploadHistoryFn() {
				let time = ''
				if (this.typedele == 0) {
					time = this.meaTime
				}
				if (this.typedele == 1) {
					time = this.displayTime
				}
				console.log('time', time);
				let obj = {
					date: time,
					rsId: this.rsId * 1,
					rainFall: this.rainFall * 1,
					informant: this.informant,
					measuringTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
					mapLon: this.mapLon,
					mapLat: this.mapLat,
					method: this.method

				}
				// 验证所有字段是否为空
				let isEmpty = false;
				let emptyFields = [];

				for (let key in obj) {
					if (obj[key] === '' || obj[key] === null || obj[key] === undefined) {
						isEmpty = true;
						emptyFields.push(key);
					}
				}

				// 特殊处理数值型字段，确保它们不是0或NaN
				if (obj.rsId === 0 || isNaN(obj.rsId) || obj.rainFall === 0 || isNaN(obj.rainFall)) {
					isEmpty = true;
					if (isNaN(obj.rsId) || obj.rsId === 0) emptyFields.push('rsId');
					if (isNaN(obj.rainFall) || obj.rainFall === 0) emptyFields.push('rainFall');
				}

				// 如果有空字段，显示错误提示
				if (isEmpty) {
					uni.showToast({
						title: `以下字段不能为空: ${emptyFields.join(', ')}`,
						icon: 'none',
						duration: 1200
					});
					return; // 停止执行后续代码
				}
				console.log('obj', obj);
				uni.$u.http.post('/api/device/device/addArtificialRainRecorderData', obj).then(res => {
					console.log('res', res);
					if (res.code == 200) {
						uni.showToast({
							title: '上传成功',
							icon: 'success',
							duration: 1500
						});
						setTimeout(() => {
							uni.navigateBack({
								delta: 2
							});
						}, 1500)
					}
				}).catch(err => {
					console.log('错误', err);
					uni.showToast({
						title: '上传失败',
						icon: 'error',
						duration: 1500
					});
				})
			},
			// 获取某一天雨量
			obtainTheRainfall(data) {
				uni.$u.http.get('/api/device/device/rainfallStationDataList', {
					params: {
						"pageSize": 1,
						"pageNum": 1,
						"date": data,
						"rsId": this.rsId * 1
					}
				}).then(res => {
					if (res.code == 200) {
						if(res.rows.length != 0){
							this.todayRainfall = res.rows[0].rainFall
						}else{
							this.todayRainfall = 0
						}
						console.log('res', res);
					} else {
						uni.showToast({
							title: '暂无数据',
							duration: 1500
						});
					}
				}).catch(err => {
					console.log('err', err);
				})
			},
			switchTime(days) {
				if (days > 0 && this.isToday) return
				const newDate = new Date(this.currentDate)
				newDate.setDate(newDate.getDate() + days)
				this.currentDate = newDate
				this.$emit('change', this.currentDate)
				// 获取某一天雨量
				setTimeout(()=>{
					this.obtainTheRainfall(this.displayTime)
				},100)
				
			}
		}
	}
</script>

<style scoped lang="scss">
	.home-container {
		padding: 30rpx;

		.header {
			margin-bottom: 30rpx;

			.station-name {
				font-size: 36rpx;
				color: #333;
				padding: 20rpx 0;

				.label {
					font-weight: bold;
					color: #555;
				}

				.value {
					color: #4a90e2;
					font-weight: 500;
				}
			}
		}

		.card {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 30rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

			&.today-rainfall {
				display: flex;
				justify-content: space-between;
				align-items: center;
				background: linear-gradient(135deg, #f0f7ff, #e1f0ff);
				border-left: 8rpx solid #4a90e2;

				.card-content {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.card-label {
						font-size: 35rpx;
						color: #666;
					}

					.rainfall-value {
						display: flex;
						align-items: baseline;

						.number {
							font-size: 48rpx;
							font-weight: bold;
							color: #4a90e2;
							margin: 0 10rpx;
						}

						.unit {
							font-size: 28rpx;
							color: #888;
						}
					}
				}

				.card-icon {
					background-color: rgba(74, 144, 226, 0.1);
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					display: flex;
					justify-content: center;
					align-items: center;

					image {
						width: 60rpx;
						height: 60rpx;
					}
				}
			}
		}

		/* 新增的表单行样式 */
		.form-row {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 30rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

			.form-item {
				display: flex;
				align-items: center;
				margin-bottom: 30rpx;

				&:last-child {
					margin-bottom: 0;
				}

				.form-label {
					font-size: 35rpx;
					color: #666;
					width: 220rpx;
					// background-color: #333;
				}

				.form-input {
					flex: 1;
					display: flex;
					align-items: center;

					.unit {
						font-size: 28rpx;
						color: #888;
						margin-left: 20rpx;
					}

					.time-switcher {
						display: flex;
						align-items: center;
						justify-content: space-between;
						width: 100%;

						.current-time {
							font-size: 32rpx;
							color: #333;
						}

						.arrow-btn {
							padding: 10rpx;

							&.disabled {
								opacity: 0.5;
							}
						}
					}
				}
			}
		}

		.action-buttons {
			margin-top: 60rpx;
		}
	}
</style>